﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Weka
{
    internal class Key
    {
        private readonly MemoryStream _ms;
        public Key(StreamReada sr)
        {
            MemoryStream ms = new MemoryStream(32);
            ReadRawStructureDataOfMessage(sr, ms);
            ms.Position = 0;
            _ms = ms;
        }

        public MemoryStream Stream { get { return _ms; } }

        public byte[] GetRawData()
        {
            byte[] data = _ms.ToArray();
            _ms.Position = 0;
            return data;
        }

        private static void ReadRawStructureDataOfMessage(StreamReada sr, MemoryStream ms)
        {
            byte fieldCount = sr.ReadByte();
            ms.WriteByte(fieldCount);
            for (int i = 0; i < fieldCount; i++)
            {
                var fi = sr.ReadFieldInfo();
                fi.Write(ms);
                if (fi.FieldType != FieldType.PrimaryData)
                    ReadRawStructureDataOfMessage(sr, ms);
            }
        }

        public void GetSubKey(int index, out Key key, out FieldInfo fieldInfo)
        {
            int j = index;

            _ms.Position = 0;
            byte fieldCount = (byte)_ms.ReadByte();

            for (int i = 0; i < fieldCount; i++)
            {
                fieldInfo = new FieldInfo(_ms);

                if (fieldInfo.FieldType == FieldType.PrimaryData) continue;

                key = new Key(new StreamReada(_ms));
                if (j-- == 0) return;
            }
            throw new Exception("Could not read message key " + index + ".");//TODO
        }

    }
}
